<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="系统自动生成" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="营销订单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderCode">
              <a-input v-model="model.orderCode" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="是否标识订单为已生成计划单"
              :labelCol="wrapperCol"
              :wrapperCol="labelCol"
              prop="isProduced"
            >
              <a-checkbox v-model="isProduced" @change="onCheckboxChange"></a-checkbox>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="特殊说明"
              :labelCol="{ xs: { span: 24 }, sm: { span: 2 } }"
              :wrapperCol="{ xs: { span: 24 }, sm: { span: 21 } }"
              prop="specialRemark"
            >
              <a-textarea v-model="model.specialRemark" rows="4" placeholder="请输入特殊说明" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="营销生产计划单子表" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="tslSaleProductionPlanDetailTable.loading"
          :columns="tslSaleProductionPlanDetailTable.columns"
          :dataSource="tslSaleProductionPlanDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          :toolbarConfig="{ slot: ['prefix', 'suffix'], btn: ['remove', 'clearSelection'] }"
          @edit-closed="handleEditClosed"
        />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { getAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'

export default {
  name: 'TslSaleProductionPlanForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
  },

  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      isProduced: true,
      model: {
        id:'',
        code:'',
        orderCode:'',
        specialRemark:'',
        isProduced:undefined
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {},
      refKeys: ['tslSaleProductionPlanDetail'],
      tableKeys: ['tslSaleProductionPlanDetail'],
      activeKey: 'tslSaleProductionPlanDetail',
      // 营销生产计划单子表
      tslSaleProductionPlanDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '营销订单编号',
            key: 'orderCode',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '订单类型',
            key: 'documentType',
            type: JVXETypes.select,
            dictCode: 'marketing_type',
            disabled: true,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '产品类型',
            key: 'productType',
            type: JVXETypes.select,
            dictCode: 'product_type',
            disabled: true,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },

          {
            title: '产品编号',
            key: 'productCode',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '产  品',
            key: 'productBatchNo',
            type: JVXETypes.normal,
            width: '300px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '配方号',
            key: 'formulaNo',
            type: JVXETypes.normal,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '订单数量',
            key: 'orderWeight',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '已计划数量',
            key: 'planedQuantity',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '已审批数量',
            key: 'approvedQuantity',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '库存',
            key: 'stockQuantity',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '库存描述',
            key: 'stockDesc',
            type: JVXETypes.input,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '计划数量',
            key: 'planQuantity',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '单位',
            key: 'weightUnit',
            type: JVXETypes.select,
            dictCode: 'zl_unit',
            width: '80px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '交货期',
            key: 'deliveryDate',
            type: JVXETypes.normal,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '下单部门',
            key: 'orderOrgCode',
            type: JVXETypes.normal,
            dictCode: 'sys_depart,depart_name,org_code',
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '下单时间',
            key: 'orderCreateTime',
            type: JVXETypes.datetime,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
        ],
      },
      url: {
        add: '/sale/tslSaleProductionPlan/add',
        edit: '/sale/tslSaleProductionPlan/edit',
        queryById: '/sale/tslSaleProductionPlan/queryById',
        tslSaleProductionPlanDetail: {
          list: '/sale/tslSaleProductionPlan/queryTslSaleProductionPlanDetailByMainId',
          listById: '/sale/tslSaleProductionPlan/queryTslSaleProductionPlanDetailByOrderIds',
        },
      },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    console.log('model=', this.model)
    if (this.customFormData != null) {
      console.log('this.customFormData=', this.customFormData)
      console.log('dis', this.formDisabled)
      this.model = this.customFormData
      this.editAfter() //现在子表内容需要
      }
  },
  methods: {
    // 单元格编辑完成之后触发的事件
    handleEditClosed(event) {
      let { $table, row, column } = event

      let field = column.property
      let cellValue = row[field]
      console.log(field, cellValue, row, '修改单元格')
      let planedQuantity = parseFloat(row.planQuantity) + parseFloat(row.planedQuantity)
      let orderWeight = parseFloat(row.orderWeight)
      if (planedQuantity > orderWeight) {
        this.$message.warning(row.productBatchNo + '总计划数量超出订单数量！')
      } else if (planedQuantity < orderWeight) {
        this.$message.warning(row.productBatchNo + '总计划数量小于订单数量！')
        this.isProduced = false
        this.model.isProduced = 0
      }
    },
    onCheckboxChange(e) {
      if (e.target.checked) {
        this.model.isProduced = 1
      } else {
        this.model.isProduced = 0
      }
    },
    add(record) {
      console.log('营销订单增加计划单：', record)
      this.model = {
        code: '',
        specialRemark: '',
        orderCode: record.code,
        isProduced: 1,
        id: '',
      }
      getAction(this.url.tslSaleProductionPlanDetail.listById, { ids: record.id }).then((res) => {
        console.log(res)
        if (res.success) {
          this.tslSaleProductionPlanDetailTable.dataSource = res.result
        }
      })
    },
    addBefore() {
      this.tslSaleProductionPlanDetailTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        this.isProduced=this.model.isProduced==1;
        console.log("是否已生成计划单：",this.isProduced,this.model);
        let params = { id: this.model.id }
        this.requestSubTableData(
          this.url.tslSaleProductionPlanDetail.list,
          params,
          this.tslSaleProductionPlanDetailTable
        )
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        tslSaleProductionPlanDetailList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
  },
}
</script>

<style scoped></style>
